package me.yan.utils;

import io.micrometer.common.util.StringUtils;
import me.yan.constant.WebConst;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class Commons {
    /**
     * 获取网站标题
     *
     * @return
     */
    public  String site_title() {
        return site_option("site_title");
    }
    /**
     * 获取google网站验证码
     *
     * @return
     */
    public  String google_site_verification() {
        return site_option("google_site_verification");
    }
    /**
     * 获取百度网站验证码
     *
     * @return
     */
    public  String baidu_site_verification() {
        return site_option("baidu_site_verification");
    }
    /**
     * 网站配置项
     *
     * @param key
     * @return
     */
    public  String site_option(String key) {
        return site_option(key, "");
    }
    /**
     * 获取网站的备案信息
     *
     * @return
     */
    public  String site_record() {
        return site_option("site_record");
    }
    /**
     * 网站链接
     *
     * @return
     */
    public String site_url() {
        return site_url("/");
    }
    /**
     * 返回网站链接下的全址
     *
     * @param sub 后面追加的地址
     * @return
     */
    public  String site_url(String sub) {
        return site_option("site_url") + sub;
    }
    /**
     * 获取GitHub地址
     *
     * @return
     */
    public  String social_github() {
        return site_option("social_github");
    }
    /**
     * 英文格式的日期
     *
     * @param unixTime
     * @return
     */
    public  String fmtdate_en(Integer unixTime) {
        String fmtdate = fmtdate(unixTime, "d,MMM,yyyy");
        String[] dateArr = fmtdate.split(",");
        String rs = "<span>" + dateArr[0] + "</span> " + dateArr[1] + "  " + dateArr[2];
        return rs;
    }
    /**
     * 格式化unix时间戳为日期
     *
     * @param unixTime
     * @param patten
     * @return
     */
    public  String fmtdate(Integer unixTime, String patten) {
        if (null != unixTime && org.apache.commons.lang3.StringUtils.isNotBlank(patten)) {
            return DateKit.formatDateByUnixTime(unixTime, patten);
        }
        return "";
    }
    public static String show_thumb(String content) {
        content = TaleUtils.mdToHtml(content);
        if (content.contains("<img")) {
            String img = "";
            String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";//<img  src   =    >
            Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
            Matcher m_image = p_image.matcher(content);
            if (m_image.find()) {
                img = img + "," + m_image.group();
                // //匹配src
                Matcher m = Pattern.compile("src\\s*=\\s*\'?\"?(.*?)(\'|\"|>|\\s+)").matcher(img);
                if (m.find()) {  //src   ='
                    return m.group(1);
                }
            }
        }
        return "";
    }
    /**
     * 返回github头像地址
     *
     * @param email
     * @return
     */
    public static String gravatar(String email) {
        String avatarUrl = "https://github.com/identicons/";
        if (org.apache.commons.lang3.StringUtils.isBlank(email)) {
            email = "user@hanshuai.xin";
        }
        String hash = TaleUtils.MD5encode(email.trim().toLowerCase());
        return avatarUrl + hash + ".png";
    }
    /**
     * 返回作品文章地址
     *
     * @param cid
     * @return
     */
    public  String photoPermalink(Integer cid) {
        return site_url("/photo/article/" + cid.toString());
    }
    /**
     * 获取社交的链接地址
     *
     * @return
     */
    public  Map<String, String> social() {
        final String prefix = "social_";
        Map<String, String> map = new HashMap<>();
        map.put("csdn", WebConst.initConfig.get(prefix + "csdn"));
        map.put("jianshu", WebConst.initConfig.get(prefix + "jianshu"));
        map.put("resume", WebConst.initConfig.get(prefix + "resume"));
        map.put("weibo", WebConst.initConfig.get(prefix + "weibo"));
        map.put("zhihu", WebConst.initConfig.get(prefix + "zhihu"));
        map.put("github", WebConst.initConfig.get(prefix + "github"));
        map.put("twitter", WebConst.initConfig.get(prefix + "twitter"));
        return map;
    }
    /**
     * 网站配置项
     *
     * @param key
     * @param defalutValue 默认值
     * @return
     */
    public  String site_option(String key, String defalutValue) {
        System.out.println("key->"+key);
        if (StringUtils.isBlank(key)) {
            return "";
        }
        String str = WebConst.initConfig.get(key);
        System.out.println(key+"->"+str);
        if (StringUtils.isNotBlank(str)) {
            return str;
        } else {
            return defalutValue;
        }
    }
    /**
     * 获取文章中的所有图片
     *
     * @param content
     * @return
     */
    public static List<String> show_all_thumb(String content) {
        Parser parser = Parser.builder()
                .extensions(Collections.singletonList(TablesExtension.create()))
                .build();
        Node document = parser.parse(content);

        ImageVisitor visitor = new ImageVisitor();
        document.accept(visitor);
        return visitor.getImageList();
    }
    /**
     * 返回blog文章地址
     *
     * @param cid
     * @return
     */
    public String blogPermalink(Integer cid) {
        return site_url("/blog/article/" + cid.toString());
    }

    /**
     * 获取随机数
     *
     * @param max
     * @param str
     * @return
     */
    public static String random(int max, String str) {
        return UUID.random(1, max) + str;
    }
    private static class ImageVisitor extends AbstractVisitor {
        private List<String> imageList = new ArrayList<>();

        @Override
        public void visit(Image image) {
            imageList.add(image.getDestination());
            visitChildren(image);
        }

        public List<String> getImageList() {
            return imageList;
        }
    }
    /**
     * 获取文章中所有的文字
     *
     * @param content
     * @return
     */
    public static List<String> show_all_p(String content) {
        Parser parser = Parser.builder()
                .extensions(Collections.singletonList(TablesExtension.create()))
                .build();
        Node document = parser.parse(content);

        TextAndLinkVisitor visitor = new TextAndLinkVisitor();
        document.accept(visitor);

        return visitor.getTextAndLinks();
    }

    private static class TextAndLinkVisitor extends AbstractVisitor {
        private List<String> textAndLinks = new ArrayList<>();

        @Override
        public void visit(Text text) {
            if (text.getParent() instanceof Link) {
                return;
            }
            textAndLinks.add("<p>" + text.getLiteral() + "</p>");
            visitChildren(text);
        }

        @Override
        public void visit(Link link) {
            String text = link.getFirstChild() instanceof Text ? ((Text) link.getFirstChild()).getLiteral() : "";
            String url = link.getDestination();
            textAndLinks.add("<p><a href='" + url + "'>" + text + "</a></p>");
            visitChildren(link);
        }

        public List<String> getTextAndLinks() {
            return textAndLinks;
        }


    }
}
